<template>
  <div class="webchatVoice">
    <audio class="audio_item" @ended="playEnd" @loadeddata="load()" :src="chatMsg.content" preload="auto">该浏览器暂不支持播放</audio>
    <div v-if="playShow">
      <img src="../../../assets/img/webchatVoice.gif" class="audio_img"><span class="audio_len muted fr">{{chatMsg.voiceSecond}}"</span>
    </div>
    <div v-else>
      <img src="../../../assets/img/webchatVoice.png" class="audio_img audio_img_transfer"><span class="audio_len muted fr">{{chatMsg.voiceSecond}}"</span>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import { WebchatModule } from '@/store/modules/webchat'
@Component({
  name: 'webchatVoice'
})
export default class WebchatVoice extends Vue {
  @Prop() private chatMsg: any
  @Prop() private sessionId: string | undefined // 会话id

  private $route: any

  private playShow = false // 播放是否停止

  private lastPlayTime = 0

  private currentTime = 0

  get playFlag () {
    return this.chatMsg.play
  }

  @Watch('playFlag')
  private playChange () {
    this.currentTime = Date.now()
    if ((this.currentTime - this.lastPlayTime) < 300) {
      return
    }
    const dom: any = this.$el.getElementsByClassName('audio_item')[0]
    if (this.playFlag) {
      this.playShow = true
      dom.play()
    } else {
      this.playShow = false
      dom.pause()
      dom.currentTime = 0 // 清0
    }
    this.lastPlayTime = Date.now()
  }

  private playEnd () {
    const arr = this.$route.path.split('/') || []
    const tabType = arr.length > 4 ? arr[3] : 'webchatDateCenter'
    WebchatModule.SET_CHAT_VOICE_PLAY({ tabType, sessionId: this.sessionId, play: false, createTimestamp: this.chatMsg.createTimestamp })
    this.playShow = false
  }

  private load () {
    const audio = this.$el.getElementsByTagName('audio')[0]
    const dom: any = this.$el.getElementsByClassName('audio_len')[0]
    let timeLen: any = audio.duration
    timeLen = Math.ceil(parseFloat(timeLen))
    dom.innerText = `${timeLen}"`
  }
}
</script>
<style lang="stylus" scoped>
  .webchatVoice
    width 160px
    height 40px
    line-height 50px
    cursor pointer
    img
      height 14px
      margin-left 14px
    .audio_len
      line-height 40px
      margin-right 14px
</style>
